package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class uploadAndDownloadController {

    //参数配置化:定义一个路劲参数在配置文件内引入对应值
    @Value("${reggie.path}")
    public String basePath;

    @PostMapping("/upload")
    public R<Object> upload(MultipartFile file) throws IOException {
        log.info("文件名:{}", file.toString());
        //获取上传文件名
        String originalFilename = file.getOriginalFilename();
        //获取上传文件后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //用uuid随机生成一个字符串
        String filename = UUID.randomUUID().toString() + suffix;
        //如果这个文件所在目录不存在则创建这个目录
        File f = new File(basePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        file.transferTo(new File(basePath, filename));
        return R.success(filename);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
         File file = new File(basePath, name);
        log.info(file.toString());
        FileInputStream fileInputStream = new FileInputStream(file);

        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");

        int len;
        byte[] bytes = new byte[1024];

        while ((len = fileInputStream.read(bytes)) != -1) {
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }

        outputStream.close();
        fileInputStream.close();
    }
}
